﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace ERPStore.Web.ModelMetadata
{
	public class ModelMetadataProvider : System.Web.Mvc.DataAnnotationsModelMetadataProvider
	{
		private IList<ModelMetaData> m_BindingCollection;

		public ModelMetadataProvider(IList<ModelMetaData> config)
			: base()
		{
			m_BindingCollection = config;
		}

		protected override System.Web.Mvc.ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
		{
			var metaData = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
			if (containerType != null)
			{
				var exisingMetadata = m_BindingCollection.SingleOrDefault(i => i.ModelType == containerType 
																		&& i.PropertyName == propertyName);
				if (exisingMetadata != null)
				{
					var model = modelAccessor.Invoke();
					metaData.IsRequired = exisingMetadata.IsRequired(model);
					if (exisingMetadata.DisplayFormatString != null)
					{
						metaData.DisplayFormatString = exisingMetadata.DisplayFormatString;
					}
					metaData.Watermark = exisingMetadata.Watermark;
					metaData.DisplayName = exisingMetadata.DisplayName;
					metaData.Description = exisingMetadata.Description;
					if (exisingMetadata.MaxStringLength > 0)
					{
						metaData.AdditionalValues.Add("MaxStringLength", exisingMetadata.MaxStringLength);
					}
					if (exisingMetadata.MinStringLength > 0)
					{
						metaData.AdditionalValues.Add("MinStringLength", exisingMetadata.MinStringLength);
					}
				}
			}
			return metaData;
		}

	}
}
